package com.company.indicationshots.activity;

import static com.company.indicationshots.activity.MainActivity.mode;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.company.indicationshots.R;
import com.company.indicationshots.adapter.FuncSettingSpinnerAdapter;
import com.company.indicationshots.database.DatabaseHelper;
import com.company.indicationshots.util.EditLoseFocus;
import com.company.indicationshots.util.EditTextClick;
import com.company.indicationshots.util.FuncSpinnerClick;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

//功能设置页面
public class FuncSettingActivity extends AppCompatActivity {

    String gunType = "95式自动步枪";
    String targetType = "光电靶";
    String bulletCount = "30";
    int gunData = 1;
    int shot = 1;
    int locationReport = 1                                                                                                                                                                                  ;
    String shootDistance = "100";
    String anotherGunType = null;
    String anotherTargetType = null;
    String anotherBulletCount = null;
    int anotherGunData = 1;
    int anotherShot = 1;
    int anotherLocationReport = 1;
    String anotherShootDistance = null;

    @SuppressLint("Range")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_func_setting);


        TextView userSet = findViewById(R.id.userSet);
        TextView commSet = findViewById(R.id.commSet);

        userSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FuncSettingActivity.this, UserSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
            }
        });

        commSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FuncSettingActivity.this, CommSettingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0); // 0表示没有动画
            }
        });

        ImageView funcClose = findViewById(R.id.funcClose);
        funcClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FuncSettingActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        DatabaseHelper dbHelper = new DatabaseHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String sql = "select gunType,targetType,bulletCount,gunData,shot,locationReport,shootDistance from funcset order by id desc";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor.moveToNext()) {
            gunType = cursor.getString(cursor.getColumnIndex("gunType"));
            targetType = cursor.getString(cursor.getColumnIndex("targetType"));
            bulletCount = cursor.getInt(cursor.getColumnIndex("bulletCount")) + "";
            gunData = cursor.getInt(cursor.getColumnIndex("gunData"));
            shot = cursor.getInt(cursor.getColumnIndex("shot"));
            locationReport = cursor.getInt(cursor.getColumnIndex("locationReport"));
            shootDistance = cursor.getInt(cursor.getColumnIndex("shootDistance")) + "";
            if (cursor.moveToNext()){
                anotherGunType = cursor.getString(cursor.getColumnIndex("gunType"));
                anotherTargetType = cursor.getString(cursor.getColumnIndex("targetType"));
                anotherBulletCount = cursor.getInt(cursor.getColumnIndex("bulletCount")) + "";
                anotherGunData = cursor.getInt(cursor.getColumnIndex("gunData"));
                anotherShot = cursor.getInt(cursor.getColumnIndex("shot"));
                anotherLocationReport = cursor.getInt(cursor.getColumnIndex("locationReport"));
                anotherShootDistance = cursor.getInt(cursor.getColumnIndex("shootDistance")) + "";
            }
        }
        cursor.close();
        db.close();

        Spinner funcGunType = findViewById(R.id.func_gun_type);
        Spinner funcTargetType = findViewById(R.id.func_target_type);
        Spinner funcMode = findViewById(R.id.func_mode);
        EditText funcBulletCountView = findViewById(R.id.func_bullet_count);

        List<String> funcGunTypeData = new ArrayList<String>() {{
            add("95式自动步枪");
            add("92式手枪");
        }};
        FuncSettingSpinnerAdapter funcGunTypeAdapter = new FuncSettingSpinnerAdapter(this, R.layout.func_spinner_item_layout, funcGunTypeData);
        funcGunType.setAdapter(funcGunTypeAdapter);
        FuncSpinnerClick.onClickSelectItem(funcGunTypeAdapter, funcGunType);
        int index = funcGunTypeData.indexOf(gunType);
        funcGunTypeAdapter.setSelectItem(index);
        funcGunType.setSelection(index);

        List<String> funcTargetTypeData = new ArrayList<String>() {{
            add("光电靶");
            add("激波靶");
        }};
        FuncSettingSpinnerAdapter funcTargetTypeAdapter = new FuncSettingSpinnerAdapter(this, R.layout.func_spinner_item_layout, funcTargetTypeData);
        funcTargetType.setAdapter(funcTargetTypeAdapter);
        FuncSpinnerClick.onClickSelectItem(funcTargetTypeAdapter, funcTargetType);
        index = funcTargetTypeData.indexOf(targetType);
        funcTargetTypeAdapter.setSelectItem(index);
        funcTargetType.setSelection(index);

        List<String> funcModeData = new ArrayList<String>() {{
            add("精度射击模式");
            add("据枪瞄准模式");
        }};
        FuncSettingSpinnerAdapter funcModeAdapter = new FuncSettingSpinnerAdapter(this, R.layout.func_spinner_item_layout, funcModeData);
        funcMode.setAdapter(funcModeAdapter);
        FuncSpinnerClick.onClickSelectItem(funcModeAdapter, funcMode);
        index = funcModeData.indexOf(mode);
        funcModeAdapter.setSelectItem(index);
        funcMode.setSelection(index);

        EditTextClick.setEditTextClickListener(funcBulletCountView, this);
        funcBulletCountView.setText(bulletCount);

        ImageView gunDataView = findViewById(R.id.gunData);
        ImageView shotView = findViewById(R.id.shot);
        ImageView locationReportView = findViewById(R.id.location_report);

        if (gunData == 1){
            gunDataView.setImageResource(R.drawable.baseline_check_20);
        } else {
            gunDataView.setImageDrawable(null);
        }

        if (shot == 1) {
            shotView.setImageResource(R.drawable.baseline_check_20);
        } else {
            shotView.setImageDrawable(null);
        }

        if (locationReport == 1) {
            locationReportView.setImageResource(R.drawable.baseline_check_20);
        } else {
            locationReportView.setImageDrawable(null);
        }

        EditText shootDistanceView = findViewById(R.id.shoot_distance);

        EditTextClick.setEditTextClickListener(shootDistanceView, this);

        shootDistanceView.setText(shootDistance);

        funcGunType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                funcGunTypeAdapter.setSelectItem(position);
                if(position == funcGunTypeData.indexOf(gunType)){
                    int index = funcTargetTypeData.indexOf(targetType);
                    funcTargetType.setSelection(index);
                    funcBulletCountView.setText(bulletCount);
                    if (gunData == 1){
                        gunDataView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        gunDataView.setImageDrawable(null);
                    }
                    if (shot == 1) {
                        shotView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        shotView.setImageDrawable(null);
                    }
                    if (locationReport == 1) {
                        locationReportView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        locationReportView.setImageDrawable(null);
                    }
                    shootDistanceView.setText(shootDistance);
                } else {
                    int index = funcTargetTypeData.indexOf(anotherTargetType);
                    funcTargetType.setSelection(index);
                    if ("95式自动步枪".equals(gunType)){
                        funcBulletCountView.setText(anotherBulletCount == null ? "8" : anotherBulletCount);
                    } else {
                        funcBulletCountView.setText(anotherBulletCount == null ? "30" : anotherBulletCount);
                    }
                    if (anotherGunData == 1){
                        gunDataView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        gunDataView.setImageDrawable(null);
                    }
                    if (anotherShot == 1) {
                        shotView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        shotView.setImageDrawable(null);
                    }
                    if (anotherLocationReport == 1) {
                        locationReportView.setImageResource(R.drawable.baseline_check_20);
                    } else {
                        locationReportView.setImageDrawable(null);
                    }
                    if ("95式自动步枪".equals(gunType)){
                        shootDistanceView.setText(anotherShootDistance == null ? "25" : anotherShootDistance);
                    } else {
                        shootDistanceView.setText(anotherShootDistance == null ? "100" : anotherShootDistance);
                    }
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        gunDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (gunDataView.getDrawable() != null) {
                    gunDataView.setImageDrawable(null);
                } else {
                    gunDataView.setImageResource(R.drawable.baseline_check_20);
                }
            }
        });

        shotView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shotView.getDrawable() != null) {
                    shotView.setImageDrawable(null);
                } else {
                    shotView.setImageResource(R.drawable.baseline_check_20);
                }
            }
        });

        locationReportView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (locationReportView.getDrawable() != null) {
                    locationReportView.setImageDrawable(null);
                } else {
                    locationReportView.setImageResource(R.drawable.baseline_check_20);
                }
            }
        });

        TextView applySet = findViewById(R.id.applySet);

        applySet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String gunType = funcGunType.getSelectedItem().toString();
                targetType = funcTargetType.getSelectedItem().toString();
                String bulletCountText = funcBulletCountView.getText().toString();
                String funcModeText = funcMode.getSelectedItem().toString();
                int bulletCount;
                if (StrUtil.isNumeric(bulletCountText)){
                     bulletCount = Integer.parseInt(bulletCountText);
                     if (bulletCount < 0){
                         return;
                     }
                } else {
                    return;
                }
                int gunData;
                if (gunDataView.getDrawable() != null) {
                    gunData = 1;
                } else {
                    gunData = 0;
                }
                int shot;
                if (shotView.getDrawable() != null) {
                    shot = 1;
                } else {
                    shot = 0;
                }
                int locationReport;
                if (locationReportView.getDrawable() != null) {
                    locationReport = 1;
                } else {
                    locationReport = 0;
                }
                String shootDistanceText = shootDistanceView.getText().toString();
                int shootDistance;
                if (StrUtil.isNumeric(shootDistanceText)) {
                    shootDistance = Integer.parseInt(shootDistanceText);
                    if (shootDistance < 0){
                        return;
                    }
                } else {
                    return;
                }
                DatabaseHelper dbHelper = new DatabaseHelper(FuncSettingActivity.this);
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                String createTime = DateUtil.format(DateUtil.date(), "yyyy/MM/dd HH:mm");

                // 开始事务
                db.beginTransaction();
                try {
                    String sql = "delete from funcset where gunType = ?";
                    db.execSQL(sql,new String[]{gunType});

                    ContentValues values = new ContentValues();
                    values.put("gunType", gunType);
                    values.put("targetType",targetType);
                    values.put("bulletCount", bulletCount);
                    values.put("gunData",gunData);
                    values.put("shot", shot);
                    values.put("locationReport", locationReport);
                    values.put("shootDistance", shootDistance);
                    values.put("createTime", createTime);
                    db.insert("funcset", null, values);

                    db.setTransactionSuccessful();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    db.endTransaction();

                    db.close();
                }

                Intent intent;
                if ("精度射击模式".equals(funcModeText)){
                    mode = funcModeText;
                    intent = new Intent(FuncSettingActivity.this, MainActivity.class);
                    intent.putExtra("gunType", gunType);
                    intent.putExtra("targetType",targetType);
                    intent.putExtra("bulletCount",bulletCount);
                    intent.putExtra("gunData",gunData);
                    intent.putExtra("shot",shot);
                    intent.putExtra("locationReport",locationReport);
                    intent.putExtra("shootDistance", shootDistance);
                    intent.putExtra("activity", "funcSetting");
                } else {
                    mode = funcModeText;
                    intent = new Intent(FuncSettingActivity.this, ShotAnalyseActivity.class);
                    intent.putExtra("bulletCount",bulletCount);
                }
                startActivity(intent);

            }
        });

        ConstraintLayout constraintLayout = findViewById(R.id.funcSetLayout);

        EditLoseFocus.loseFocus(constraintLayout,this,funcBulletCountView);
        EditLoseFocus.loseFocus(constraintLayout,this,shootDistanceView);

    }
}